<template>
  <a-drawer v-model:visible="visible" class="custom-class" title="全局配置-背景设置" placement="right" width="400"
    :maskClosable="false">
    <a-tabs v-model:activeKey="activeTab" type="card" @change="changeTab">
      <a-tab-pane :key="1" tab="固定颜色">
        <div class="cube" :style="{ backgroundColor: `${background?.rgba}` }" @click="colorPickerClick('bg', $event)">
          <color-picker class="colorPicker" modebar="none" :show-opacity="false" @change="colorChange" :btn-style="{
            width: '60px',
            height: '32px',
            marginLeft: 'auto',
            display: 'none',
          }" />
        </div>
      </a-tab-pane>

      <a-tab-pane :key="4" tab="背景虚化">
        <div style="display: flex; align-items: center; gap: 20px;">
          <span>背景虚化：</span>
          <a-switch v-model:checked="checked" />
        </div>
      </a-tab-pane>

      <a-tab-pane :key="2">
        <template #tab>
          <span>
            自定义
          </span>
        </template>
        <p style="color: rgb(115, 122, 135)">
          选择多个背景时，算法将为镜头组视频智能推荐不同的背景
        </p>
        <div class="colorList">
          <div class="color-item-upload">
            <div class="color-item-upload-add">
              <span>+</span>
            </div>
            <div class="color-item-uploadOpreat">
              <span class="color-item-upload-top" @click="addVisible = true"><upload-outlined />素材库导入</span>
            </div>
          </div>
          <div class="color-item" v-for="(item, index) in material_urlsArr" :key="item?.url">
            <img style="height: 100%;width: 100%;object-fit: contain" v-lazy="item.url" alt="" />
            <div class="close" @click="deleteItem(item)">
              <close-outlined />
            </div>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane :key="3">
        <template #tab>
          <span>
            内置图片
          </span>
        </template>
        <p style="color: rgb(115, 122, 135)">
          选择多个背景时，算法将为镜头组视频智能推荐不同的背景
        </p>
        <div class="checkCount" style="text-align: right;">
          <span v-if="builtInImageCheckCount > 0">已选择{{ builtInImageCheckCount }}</span>
          <a-button type="link" size="small" @click="builtInImageCheckAll()">全选</a-button>
          <a-button type="link" size="small" @click="cancelBuiltInImage(false)">全部取消</a-button>
        </div>
        <div class="colorList">
          <div class="color-item" @click="builtInImageCheck(item, index)" v-for="(item, index) in builtInImageList"
            :key="item?.url">
            <img style="height: 100px;width: 100%; object-fit: contain" alt="" v-lazy="item.url
              " />
            <a-checkbox class="check_btn" v-if="item?.isCheck" v-model:checked="item.isCheck"></a-checkbox>
          </div>
        </div>
      </a-tab-pane>
      <template #rightExtra>
        <a-button v-show="activeTab == 2 && material_urlsArr.length > 0" type="link" @click="clear">清空</a-button>
      </template>
    </a-tabs>
    <template #footer>
      <a-row type="flex" justify="end">
        <a-button style="margin-right: 8px" type="primary" @click="onClose('submit')">确认添加</a-button>
        <a-button @click="onClose('close')">取消</a-button>
      </a-row>
    </template>
    <!-- 素材库导入 -->
    <ChooseMaterial :haveTags="[
      {
        name: '网络素材',
        key: 'system_materials',
      }
    ]" useType="视频背景" :isClip="false" material_type="image" :visible="addVisible" @close="cancel" :multiple="true" />

    <!-- <newChooseMaterial
    :isClip="false"
    :visible="addVisible"
    modelType = "image"
    @close="cancel"
    /> -->
  </a-drawer>
</template>
<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  onMounted,
  ref,
} from "vue";
import { useStore } from "vuex";

import ColorPicker from "colorpicker-v3";
import "colorpicker-v3/style.css";
import {
  QuestionCircleOutlined,
  UploadOutlined,
  CloudUploadOutlined,
  CaretRightOutlined,
  CloseOutlined,
} from "@ant-design/icons-vue";
// 选择文件组件
import newChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/newChooseMaterial.vue";

import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import { message } from "ant-design-vue";
// 封装的请求
import request from "@/common/utils/request";
export default defineComponent({
  components: {
    newChooseMaterial,
    QuestionCircleOutlined,
    UploadOutlined,
    CloudUploadOutlined,
    CaretRightOutlined,
    CloseOutlined,
    ColorPicker,
    ChooseMaterial,
  },
  setup() {
    const state = reactive({
      background: {}, //背景设置集合
      visible: false, //控制页面显示隐藏
      activeTab: 1, //当前切换的tab
      addVisible: false, //控制素材库组件显示隐藏
      // 背景虚化开关
      checked:false
    });
    let material_urlsArr = ref([]); //自定义背景图片集合
    let builtInImageList = ref([])//内置图片集合
    // 仓库
    const store = useStore();
    // 打开弹窗
    const showDrawer = () => {
      getBuiltInImage()//获取内置图片列表
      // 初始化背景设置所需要的数据
      state.background = JSON.parse(
        JSON.stringify(store.state.videoMixCut.VideoMashup.background)
      );

      if (state.background.type == 2) {
        //回显自定义背景图片集合
        material_urlsArr.value = state.background?.material_urls || [];
      }
      // 判断打开页面是否是未设置全局背景
      if (state.background.type == 0) {
        state.activeTab = 1;
      }

      if (state.background.type == 4) {
        state.checked = true
      } else {
        state.checked = false
      }
      // else {
      //   state.activeTab = state.background.type;
      // }

      state.activeTab = state.background.type||0
      console.log(state.background, "全局背景设置页面打开");
      state.visible = true;

    };
    // 关闭弹窗
    const onClose = (type) => {
      // 提交
      if (type == "submit") {
        // 判断用户切换到自定义背景设置为选择自定义图片直接提交
        if (state.activeTab == 2) {
          if (material_urlsArr.value?.length <= 0) {
            return message.error("请选择自定义背景图片");
          } else {
            state.background.material_urls = JSON.parse(JSON.stringify(material_urlsArr.value))
          }
        }
        if (state.activeTab == 3) {
          if (builtInImageCheckCount.value <= 0) {
            return message.error('请选择内置背景图片')
          } else {
            let filterList = builtInImageList.value.filter(item => item.isCheck)
            state.background.material_urls = filterList.map(item => {
              return {
                media_id: item.media_id,
                url: item.url
              }
            })
          }
        }
        
        if (state.activeTab == 4  && !state.checked) {
          state.background.type = 1
        } else {
          state.background.type = state.activeTab;
        }
        // 更新仓库
        store.dispatch("videoMixCut/SetVideoMashupItem", {
          key: "background",
          value: state.background,
        });
      }
      state.visible = false;
      material_urlsArr.value = []
      builtInImageList.value = []
    };
    // tab栏切换
    const changeTab = (e) => {
      state.activeTab = e;
      if (state.activeTab == 4) {
        state.checked = true 
      } else {
        state.checked = false
      }
    };
    // 设置背景颜色
    const colorPickerClick = (type, ev) => {
      state.openType = type;
      const target = ev.target;
      console.log(ev, "时间对象");
      // 获取元素的位置信息，getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。
      const rect = target.getBoundingClientRect();
      // 计算元素右侧边缘到视口左侧的距离
      const dom = document.querySelector(".zs-color-picker-btn-color");
      dom.click();

      // 获取视口的宽度
      const viewportWidth = window.innerWidth;

      // 计算元素距离屏幕右侧的距离
      const rightDistanceToViewportLeft = rect.right;
      const rightDistanceToViewportRight = +(
        viewportWidth - rightDistanceToViewportLeft
      ).toFixed(0);
      const top = (rect.top + 30).toFixed(0);
      // 修改弹窗的位置为当前点击元素的位置下方
      const pickerDom = document.querySelector(".zs-color-picker-panel");
      const pickerDomAll = document.querySelectorAll(".zs-color-picker-panel");
      // var parent2 = document.querySelector(".ant-drawer-body");
      // parent2.appendChild(pickerDom);

      pickerDom.style.position = "fixed";
      pickerDom.style.top = top + "px";
      pickerDom.style.right = rightDistanceToViewportRight + "px";
      console.log(pickerDom, "pickerDom");
      console.log(pickerDomAll, "pickerDomAll");
      // pickerDom.style.zIndex = "99999999999";
      // console.log(pickerDom,'pickerDom');
    };
    // 背景色change事件
    const colorChange = (color) => {
      console.log(color, "颜色改变");
      state.background.rgba = color.hex;
      // state.backgroundColor = color.hex;
    };

    // 选择文件组件回调
    const cancel = (info) => {
      if (Array.isArray(info) && info.length) {
        console.log(info, '选择的素材列表');
        info.forEach((item) => {
          const index = material_urlsArr.value.findIndex((ele) => ele.url == item.material_url);
          if (index == -1) {
            material_urlsArr.value.push({
              url: item.material_url,
              media_id: item?.oss_media_id || '',
            });
          }
        });
      }
      console.log(material_urlsArr.value, "添加之后的背景内容");

      state.addVisible = false;
    };
    // 删除某个已选择图片
    const deleteItem = (item) => {
      const index = material_urlsArr.value.findIndex((ele) => ele.url == item.url);
      index != -1 && material_urlsArr.value.splice(index, 1);
      ;
    };
    // 清空选择的图片
    const clear = () => {
      material_urlsArr.value = [];
    };
    // 获取内置图片列表
    const getBuiltInImage = () => {
      request.get('/work_ai', '/user/shotstack/material/cloud/bgi/list').then(res => {
        builtInImageList.value = res.result.MediaInfos.map(item => {
          return {
            media_id: item?.MediaId || '',
            url: item?.FileInfoList[0]?.FileBasicInfo?.FileUrl || '',
            isCheck: false
          }
        })
        if (state.background.type == 3) {
          state.background?.material_urls.forEach(bg => {
            const foundItem = builtInImageList.value.find(ele => ele.media_id === bg.media_id);
            if (foundItem) {
              foundItem.isCheck = true;
            }
          });
          console.log(builtInImageList.value)
        }
      }).catch(err => {
        console.log(err)
      })
    }
    // 单选内置图片
    const builtInImageCheck = (item, index) => {
      builtInImageList.value[index].isCheck = !builtInImageList.value[index].isCheck
    }
    // 全选内置图片
    const builtInImageCheckAll = () => {
      builtInImageList.value.forEach(item => item.isCheck = true)
    }
    // 反选内置图片
    const cancelBuiltInImage = () => {
      builtInImageList.value.forEach(item => item.isCheck = false)
    }
    // 获取内置图片选中个数
    const builtInImageCheckCount = computed(() => {
      if (builtInImageList.value.length) {
        return builtInImageList.value.filter(item => item.isCheck).length
      } else {
        return 0
      }
    })
    return {
      ...toRefs(state),
      showDrawer,
      onClose,
      changeTab,
      colorPickerClick,
      colorChange,
      cancel,
      deleteItem,
      clear,
      material_urlsArr,
      getBuiltInImage,
      builtInImageList,
      builtInImageCheck,
      builtInImageCheckCount,
      builtInImageCheckAll,
      cancelBuiltInImage
    };
  },
});
</script>
<style lang="less" scoped>
.cube {
  width: 30px;
  height: 30px;
  border-radius: 5px;
  position: relative;
}

.colorList {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  max-height: 600px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 8px;
    /* 滚动条的宽度 */
    height: 10px;
    /* 滚动条的高度，垂直滚动条可能用得上 */
    display: none;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    /* 滑块的背景颜色 */
    border-radius: 10px;
    /* 滑块的圆角 */

  }
}

.color-item,
.color-item-upload {
  cursor: pointer;
  height: 100px;
  margin-top: 10px;
  background: #f7f7f7;
  border: 1px solid #e6e6e7;
  border-radius: 5px;

  .check_btn {
    position: absolute;
    top: 0;
    left: 0;
  }
}

.color-item-upload {
  background: #f7f7f7;

  .color-item-upload-add {
    width: 100%;
    font-size: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .color-item-uploadOpreat {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    height: 100%;
    visibility: hidden;
    cursor: pointer;

    .color-item-upload-top,
    .color-item-upload-bottom {
      display: flex;
      height: 49%;
      align-items: center;
      justify-content: center;
    }

    .color-item-upload-top:hover,
    .color-item-upload-bottom:hover {
      color: #2878ff;
    }

    .color-item-upload-middle {
      height: 1px;
      width: 80%;
      background: #e6e6e7;
    }
  }
}

.color-item-upload:hover .color-item-uploadOpreat {
  visibility: visible;
}

.color-item-upload:hover .color-item-upload-add {
  display: none;
}

.color-item {
  position: relative;
}

.close {
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  position: absolute;
  right: 0;
  top: 0;
  font-size: 10px;
  border-radius: 10px;
  border: 1px solid #c1c1c1;
  background: #fff;
  visibility: hidden;
}

.color-item:hover .close {
  visibility: visible;
}

.colorPicker {
  background: skyblue;
}
</style>
